package com.jielin.handling.service.dzzj.impl;

import com.alibaba.fastjson.JSONObject;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.jielin.handling.entity.auditresult.AuditResult;
import com.jielin.handling.entity.dzzj.OrgAndJYIp;
import com.jielin.handling.entity.dzzj.RetrunVideo;
import com.jielin.handling.entity.dzzj.ReturnJson;
import com.jielin.handling.entity.dzzj.Video;
import com.jielin.handling.entity.material.MaterialFile;
import com.jielin.handling.entity.material.MaterialType;
import com.jielin.handling.entity.material.MaterialTypeDocument;
import com.jielin.handling.entity.tsuspect.TSuspec;
import com.jielin.handling.entity.video.PubliceVideo;
import com.jielin.handling.entity.vo.PoliceVo;
import com.jielin.handling.exception.ResultEnum;
import com.jielin.handling.mapper.auditresult.AuditResultMapper;
import com.jielin.handling.mapper.dzzj.VideoMapper;
import com.jielin.handling.mapper.material.MaterialFileMapper;
import com.jielin.handling.mapper.material.MaterialTypeDocumentMapper;
import com.jielin.handling.mapper.material.MaterialTypeMapper;
import com.jielin.handling.mapper.police.PoliceCaseMapper;
import com.jielin.handling.mapper.police.PoliceManMapper;
import com.jielin.handling.mapper.tsuspect.TSuspecMapper;
import com.jielin.handling.service.dzzj.VideoService;
import com.jielin.handling.service.xsky.XskyService;
import com.jielin.handling.util.*;
import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.InputFormatException;
import it.sauronsoftware.jave.MultimediaInfo;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.lang.StringUtils;
import org.apache.http.entity.ContentType;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class VideoServiceImpl implements VideoService {
    public static double pers = 1048576; // 1024*1024
    @Autowired
    private VideoMapper videoMapper;
    @Autowired
    private MaterialTypeDocumentMapper documentMapper;
    @Autowired
    private MaterialFileMapper fileMapper;
    @Autowired
    private MaterialTypeMapper maTypeMapper;
    @Autowired
    private PoliceManMapper policeManMapper;

    @Autowired
    PoliceCaseMapper policeCaseMapper;

    @Autowired
    private XskyService xskyService;

    @Autowired
    private TSuspecMapper tSuspecMapper;

    @Autowired
    private AuditResultMapper auditResultMapper;

    private ObjectMapper objectMapper = new ObjectMapper();
    private List<Video> videos = new ArrayList<>();

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public int saveRecorderFileCorrelation(String recorderFileId, String docId, String fileName, String fileUrl,
                                           String fileType, String thumburl) {
        int flag = -1;

        // 根据文件夹id查询文件夹信息
        MaterialTypeDocument map = documentMapper.findDocumentById(docId);

        log.info("MaterialTypeDocument:{}", JSONObject.toJSONString(map));

        MaterialType mt = new MaterialType();
        if (map == null || StringUtil.isEmpty(recorderFileId) || StringUtil.isEmpty(docId)
                || StringUtil.isEmpty(fileName) || StringUtil.isEmpty(fileUrl)) {
            return -2;
        } else {
            mt = maTypeMapper.findById(map.getMaterialtypeid());// 一级目录信息
            log.info("MaterialType:{}", JSONObject.toJSONString(mt));
        }
        // 文件存放路径==》 案件名称-警员id-案件编号/嫌疑人姓名/一级目录名称/二级文件夹名称/
        String rootpath = mt.getCasename() + "-" + mt.getUploadpoliceid() + "-" + mt.getCasecode() + File.separator
                + mt.getCaseSuspectName() + File.separator + mt.getMaterialtypename() + File.separator
                + map.getDocumentname();

        // 自定义的文件名称
        String trueFileName = String.valueOf(System.currentTimeMillis());
        // 设置存放图片文件的路径
        String filedocpath = ConstantUtil.FILE_PATH + rootpath + File.separator;
        File docment = new File(filedocpath);
        if (!docment.exists()) {
            docment.mkdirs();
        }
        fileType = fileUrl.substring(fileUrl.lastIndexOf("."));// 截取文件类型

        /*
         * if (fileType == null || fileType == "") { fileType = ".jpg"; } else if
         * (fileType.equals("1")) { fileType = ".jpg"; } else if (fileType.equals("2"))
         * { fileType = ".mp4"; } else { fileType = ".mp3"; }
         */

        String path = "";// 警翼源文件

        String thumbnailtruePath = "";// 警翼源文件缩略图存放路径
        try {
            String uploadPath = filedocpath + trueFileName + fileType;
            // 源文件
            URL url = new URL(fileUrl);
            BufferedInputStream in = new BufferedInputStream(url.openStream());
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(uploadPath));
            byte[] buff = new byte[1024 * 10];
            int count = 0;
            while ((count = in.read(buff)) != -1) {
                bos.write(buff, 0, count);
            }
            bos.close();
            path = uploadPath;

            // 源文件缩略图存放路径
            String uploadThumbnailtruePath = filedocpath + trueFileName + "thumbnail"
                    + thumburl.substring(thumburl.lastIndexOf("."));

            // 源文件缩略图
            URL thumb = new URL(thumburl);
            BufferedInputStream thumbUrlin = new BufferedInputStream(thumb.openStream());
            BufferedOutputStream thumburlbos = new BufferedOutputStream(new FileOutputStream(uploadThumbnailtruePath));
            byte[] thumburlbuff = new byte[1024 * 10];
            int thumburlcount = 0;
            while ((thumburlcount = thumbUrlin.read(thumburlbuff)) != -1) {
                thumburlbos.write(thumburlbuff, 0, thumburlcount);
            }
            thumburlbos.close();

            thumbnailtruePath = uploadThumbnailtruePath;

        } catch (Exception e) {
            log.error("警翼文件URL请求下载失败！");
            return -2;
        }

        String trueFileType = fileType.substring(1);
        // 上传源文件到xsky
        if (trueFileType.matches("^(jpg|png|JPG|PNG)$")) {
            // xskyService.uploadObject(ConstantUtil.XSKY_BUCKET_PHOTO, path, new
            // File(path));
        } else if (trueFileType.matches("^(mp4|MP4|avi|AVI|MOV|mov)$")) {
            // xskyService.uploadObject(ConstantUtil.XSKY_BUCKET_VIDEO, path, new
            // File(path));
        } else if (trueFileType.matches("^(wav|WAV|mp3|cd|CD|MP3)$")) {
            // xskyService.uploadObject(ConstantUtil.XSKY_BUCKET_AUDIO, path, new
            // File(path));
        }
        // 上传源文件缩略图到xsky
        // xskyService.uploadObject(ConstantUtil.XSKY_BUCKET_PHOTO, thumbnailtruePath,
        // new File(thumbnailtruePath));

        MaterialFile materialFile = new MaterialFile();
        materialFile.setId(StringUtil.generatorUUID());
        materialFile.setMaterialtypedocumentid(docId);
        materialFile.setFiletype(fileType);
        materialFile.setUrl(path);
        materialFile.setFilename(fileName);
        materialFile.setThumbnailpath(thumbnailtruePath);

        log.info("MaterialFile:{}", JSONObject.toJSONString(materialFile));
        try {
            // 插入文件记录
            fileMapper.addFile(materialFile);

            // 更改记录仪文件原件关联信息
            videoMapper.updateRecorderFileCorrelation("1", materialFile.getId(), mt.getCasecode(), mt.getId(),
                    mt.getCasesuspectid(), recorderFileId);

            // 增加文件夹数量
            documentMapper.updateDocAddCount(map.getId());

            flag = 1;
        } catch (Exception e) {
            log.info("saveRecorderFileCorrelation 事务回滚:{}", e);
            // 抛出异常让其回滚
            throw new RuntimeException("事务回滚");
        }
        return flag;
    }

    @Override
    public List<Video> findRecorderFileList(String policeCode, String fileType, String startTime, String endTime,
                                            String correlationStatus, String caseCode, String caseName) {
        if (StringUtil.isEmpty(policeCode)) {
            return null;
        }
        return videoMapper.findRecorderFileList(policeCode, fileType, startTime, endTime, correlationStatus, caseCode,
                caseName);
    }

    @Override
    public void makeInsertGrapherVideo() {
        try {
            videos.clear();
            String beginTime = getPerDateString();
            List<Map<String, String>> list = videoMapper.selectGrapherConfigure();
            for (Map<String, String> gc : list) {
                findDataInsertTable(gc.get("ip"), gc.get("port"), beginTime);
            }
            if (videos.size() > 0) {
                for (Video v : videos) {
                    v.setId(StringUtil.generatorUUID());
                }
                videoMapper.insertVideoMessage(videos);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 根据ip和port拼接接口获取数据并插入到表格中
     *
     * @param ip        服务器ip
     * @param port      服务器端口号
     * @param beginTime 开始时间
     * @return
     */
    private void findDataInsertTable(String ip, String port, String beginTime) {
        try {
            HttpClientForJL httpClientForJL = new HttpClientForJL();

            Map<String, String> headMap = new HashMap<>();
            headMap.put("_a", "getmedia");
            headMap.put("begin_time", beginTime);
            int page = 0; // 查询的页数,每页50条记录

            String uri = "http://" + ip + ":" + port + "/"; // 访问路径
            int count = 0; // 查询到的记录条数
            do {
                page++;

                headMap.put("page", String.valueOf(page));
                String jsonData = httpClientForJL.doGet(uri, headMap, "utf-8");
                if (!StringUtils.isEmpty(jsonData)) {
                    // 需要将json转化为对象
                    ReturnJson obj = objectMapper.readValue(jsonData, ReturnJson.class);
                    count = (int) obj.getHeader().get("count");
                    if (count > 0) {
                        packageBodyData(obj.getBody());
                    }
                }
            } while (count == 50);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /* 将body中的数据封装到video的对象集合当中 */
    private void packageBodyData(List list) throws Exception {
        for (int i = 0; i < list.size(); i++) {
            String s = objectMapper.writeValueAsString(list.get(i));
            RetrunVideo v = objectMapper.readValue(s, RetrunVideo.class);
            /* 设置媒体类型 */
            String file_type = v.getFile_type();
            if (file_type.matches("^(jpg|png|JPG|PNG)$")) {
                v.setFile_type("1");
            } else if (file_type.matches("^(mp4|MP4|avi|AVI|MOV|mov)$")) {
                v.setFile_type("2");
            } else if (file_type.matches("^(wav|WAV|mp3|cd|CD|MP3)$")) {
                v.setFile_type("3");
            }
            int exist = videoMapper.findDataIsExist(v.getData_id());
            Video video = null;
            if (exist == 0) {
                video = new Video();
                video.setDataId(v.getData_id());
                video.setCaptureDate(v.getCapture_date());
                video.setDeviceNo(v.getDevice_no());
                video.setCreationDate(v.getCreation_date());
                video.setMediaName(v.getMedia_name());
                video.setFileName(v.getFile_name());
                video.setPoliceNo(v.getPolice_no());
                video.setOrgNo(v.getOrg_no());
                video.setOrgName(v.getOrg_name());
                video.setFileType(v.getFile_type());
                video.setServerurl(v.getServerurl());
                video.setPlayPosition(v.getPlayposition());
                video.setThumb(v.getThumb());
                video.setFileLength(v.getFile_length());
                video.setFileDuration(v.getFile_duration());
                video.setMediaDesc(v.getMedia_desc());
                video.setUploadStationIp(v.getUpload_station_ip());
                video.setUploadStation(v.getUpload_station());
                video.setThumburlDef(v.getThumburl_def());
                video.setThumburl(v.getThumburl());
                video.setPlayurl(v.getPlayurl());
                videos.add(video);
            }
        }
    }

    /* 获取要查询数据起始时间的字符串 */
    private String getPerDateString() throws Exception {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        date = calendar.getTime();

        return sdf.format(date);
    }

    @Override
    public List<Map> findCaseAVCorrelationRate(String unitCode) {
        if (StringUtil.isEmpty(unitCode)) {
            return null;
        }
        // TODO 传入的参数为正规的单位编号(警综的)，需要查询到警翼的单位编号
        String JYOrgNo = videoMapper.findTureOrgNoByJYOrgNo(unitCode);// 警翼的单位编号
        return videoMapper.findCaseAVCorrelationRate(JYOrgNo == null ? unitCode : JYOrgNo, "1");
    }

    @Override
    public List<Map> findRateByUnitCode(String unitCode) {
        if (StringUtil.isEmpty(unitCode)) {
            return null;
        }
        // TODO 传入的参数为正规的单位编号(警综的)，需要查询到警翼的单位编号
        String JYOrgNo = videoMapper.findTureOrgNoByJYOrgNo(unitCode);// 警翼的单位编号
        return videoMapper.findRateByUnitCode(JYOrgNo == null ? unitCode : JYOrgNo, "1");
    }

    @Override
    public List<Map> findRateByPoliceCode(String policeCode, String policeId) {
        if (StringUtil.isEmpty(policeCode) || StringUtil.isEmpty(policeId)) {
            return null;
        }
        return videoMapper.findRateByPoliceCode(policeId, policeCode, "1");
    }

    @Override
    public Video findRecorderFileById(String id) {
        if (StringUtil.isEmpty(id)) {
            return null;
        }
        return videoMapper.findRecorderFileById(id);
    }

    @Override
    public OrgAndJYIp findRecorderIPbyOrgNo(String orgNo) {
        return videoMapper.findRecorderIPbyOrgNo(orgNo);
    }

    @Override
    public List<Video> selectRandomVideo(Map map) {
        List<Video> list = videoMapper.selectRandomVideo(map);
        return list;
    }

    @Override
    public List<Video> selectLatesVideo(Map map) {
        List<Video> list = videoMapper.selectLatesVideo(map);
        for (Video video1 : list) {
            if ("0".equals(video1.getFileLength()) || video1.getFileLength() == null) {
                video1.setFileLength("0MB");
            } else if (video1.getFileLength().contains(".")) {
                video1.setFileLength(video1.getFileLength() + "MB");
            } else {
                video1.setFileLength(sizeFormatNum2String(Long.valueOf(video1.getFileLength())));
            }
            if (video1.getFileDuration() != null && video1.getFileDuration() > 0) {
                Long fileDuration = video1.getFileDuration();// 时间毫秒数需要转10:05:02
                String str = formatTime(fileDuration);
                video1.setFormatToTime(str);
            } else {
                video1.setFormatToTime("00:00:00");
            }
        }
        return list;
    }

    @Override
    public List<Video> selectRecommend(Map map) {
        List<Video> list = videoMapper.selectRecommend(map);
        for (Video video1 : list) {
            if ("0".equals(video1.getFileLength()) || video1.getFileLength() == null) {
                video1.setFileLength("0MB");
            } else if (video1.getFileLength().contains(".")) {
                video1.setFileLength(video1.getFileLength() + "MB");
            } else {
                video1.setFileLength(sizeFormatNum2String(Long.valueOf(video1.getFileLength())));
            }
            if (video1.getFileDuration() != null && video1.getFileDuration() > 0) {
                Long fileDuration = video1.getFileDuration();// 时间毫秒数需要转10:05:02
                String str = formatTime(fileDuration);
                video1.setFormatToTime(str);
            } else {
                video1.setFormatToTime("00:00:00");
            }
            if (video1.getPoliceNameAndPoliceNo().equals("/")) {
                video1.setPoliceNameAndPoliceNo("");
            }
        }
        return list;
    }

    @Override
    public List<Video> selectRandomSampling2(Video video) {
        log.info("video:{}", JSONObject.toJSONString(video));
        List<Video> videos = new ArrayList<>();
        try {
            if ("0".equals(video.getVideoType())) {
                PageHelper.startPage(video.getPageNum(), video.getPageSize());
                System.out.println("---------11111111111111111111111" + new Date());
                videos = videoMapper.selectRandomSampling(video);
                System.out.println("=========22222222222222222222222" + videos.size());
                System.out.println("=========22222222222222222222222" + new Date());

//				for(Video vo1:videos1){
//					videos.add(vo1);
//				}
//				List<Video> videos2 = videoMapper.selectRandomSampling2(video);
//				for(Video vo2:videos2){
//					videos.add(vo2);
//				}
//				List<Video> videos3 = videoMapper.selectRandomSampling3(video);
//				for(Video vo3:videos3){
//					videos.add(vo3);
//				}
//				List<Video> videos4 = videoMapper.selectRandomSampling4(video);
//				for(Video vo4:videos4){
//					videos.add(vo4);
//				}
            }
            if ("1".equals(video.getVideoType())) {
                PageHelper.startPage(video.getPageNum(), video.getPageSize());
                videos = videoMapper.selectCaseVideo(video);
            }
            if ("2".equals(video.getVideoType())) {
                PageHelper.startPage(video.getPageNum(), video.getPageSize());
                videos = videoMapper.selectLawEnforcementVideo(video);
            }
            if ("4".equals(video.getVideoType())) {
                PageHelper.startPage(video.getPageNum(), video.getPageSize());
                videos = videoMapper.selectPublicVideo(video);
            }
            if ("3".equals(video.getVideoType())) {
                PageHelper.startPage(video.getPageNum(), video.getPageSize());
                videos = videoMapper.selectCarVideo(video);
            }
            if ("5".equals(video.getVideoType())) {
                PageHelper.startPage(video.getPageNum(), video.getPageSize());
                videos = videoMapper.selectOtherVideo(video);
            }
            if (videos != null && videos.size() > 0) {
                for (Video video1 : videos) {
                    if ("0".equals(video1.getFileLength()) || video1.getFileLength() == null) {
                        video1.setFileLength("0MB");
                    } else if (video1.getFileLength().contains(".")) {
                        video1.setFileLength(video1.getFileLength() + "MB");
                    } else {
                        video1.setFileLength(sizeFormatNum2String(Long.valueOf(video1.getFileLength())));
                    }
                    if (video1.getFileDuration() != null && video1.getFileDuration() > 0) {
                        Long fileDuration = video1.getFileDuration();// 时间毫秒数需要转10:05:02
                        String str = formatTime(fileDuration);
                        video1.setFormatToTime(str);
                    } else {
                        video1.setFormatToTime("00:00:00");
                    }
                }
            }
        } catch (Exception e) {
            log.error("查询异常={}", e);
        }
        return videos;
    }

    @Override
    public List<Video> selectRandomSampling(Video video) {
        List<Video> videos = new ArrayList<>();
        try {
            if ("0".equals(video.getVideoType())) {
                PageHelper.startPage(video.getPageNum(), video.getPageSize());
                videos = videoMapper.selectRandomSampling(video);
                for (Video vos : videos) {
                    if (StringUtil.isEmpty(vos.getCaseCode())) {
                        vos.setCaseName("");
                    } else {
                        vos.setCaseName(policeCaseMapper.findCaseNameByCaseCode(vos.getCaseCode()));
                    }
                }
                formater(videos);
                return videos;
//				for(Video vo1:videos1){
//					videos.add(vo1);
//				}
//				List<Video> videos2 = videoMapper.selectRandomSampling2(video);
//				for(Video vo2:videos2){
//					videos.add(vo2);
//				}
//				List<Video> videos3 = videoMapper.selectRandomSampling3(video);
//				for(Video vo3:videos3){
//					videos.add(vo3);
//				}
//				List<Video> videos4 = videoMapper.selectRandomSampling4(video);
//				for(Video vo4:videos4){
//					videos.add(vo4);
//				}
            }
            if ("1".equals(video.getVideoType())) {
                PageHelper.startPage(video.getPageNum(), video.getPageSize());
                videos = videoMapper.selectCaseVideo(video);
                for (Video vos : videos) {
                    if ("/".equals(vos.getPoliceNameAndPoliceNo())) {
                        vos.setPoliceNameAndPoliceNo("");
                    }
                    if (StringUtil.isEmpty(vos.getCaseCode())) {
                        vos.setCaseName("");
                    } else {
                        vos.setCaseName(policeCaseMapper.findCaseNameByCaseCode(vos.getCaseCode()));
                    }
                }
                formater(videos);
                return videos;
            }
            if ("2".equals(video.getVideoType())) {
                PageHelper.startPage(video.getPageNum(), video.getPageSize());
                videos = videoMapper.selectLawEnforcementVideo(video);
                for (Video vos : videos) {
                    if ("/".equals(vos.getPoliceNameAndPoliceNo())) {
                        vos.setPoliceNameAndPoliceNo("");
                    }
                    if (StringUtil.isEmpty(vos.getCaseCode())) {
                        vos.setCaseName("");
                    } else {
                        vos.setCaseName(policeCaseMapper.findCaseNameByCaseCode(vos.getCaseCode()));
                    }
                }
                formater(videos);
                return videos;
            }
            if ("4".equals(video.getVideoType())) {
                PageHelper.startPage(video.getPageNum(), video.getPageSize());
                videos = videoMapper.selectPublicVideo(video);
                for (Video vos : videos) {
                    if ("/".equals(vos.getPoliceNameAndPoliceNo())) {
                        vos.setPoliceNameAndPoliceNo("");
                    }
                    if (StringUtil.isEmpty(vos.getCaseCode())) {
                        vos.setCaseName("");
                    } else {
                        vos.setCaseName(policeCaseMapper.findCaseNameByCaseCode(vos.getCaseCode()));
                    }
                }
                formater(videos);
                return videos;
            }
            if ("3".equals(video.getVideoType())) {
                PageHelper.startPage(video.getPageNum(), video.getPageSize());
                videos = videoMapper.selectCarVideo(video);
                for (Video vos : videos) {
                    if ("/".equals(vos.getPoliceNameAndPoliceNo())) {
                        vos.setPoliceNameAndPoliceNo("");
                    }
                    if (StringUtil.isEmpty(vos.getCaseCode())) {
                        vos.setCaseName("");
                    } else {
                        vos.setCaseName(policeCaseMapper.findCaseNameByCaseCode(vos.getCaseCode()));
                    }
                }
                formater(videos);
                return videos;
            }
            if ("5".equals(video.getVideoType())) {
                PageHelper.startPage(video.getPageNum(), video.getPageSize());
                videos = videoMapper.selectOtherVideo(video);
                for (Video vos : videos) {
                    if ("/".equals(vos.getPoliceNameAndPoliceNo())) {
                        vos.setPoliceNameAndPoliceNo("");
                    }
                    if (StringUtil.isEmpty(vos.getCaseCode())) {
                        vos.setCaseName("");
                    } else {
                        vos.setCaseName(policeCaseMapper.findCaseNameByCaseCode(vos.getCaseCode()));
                    }
                }
                formater(videos);
                return videos;
            }
        } catch (Exception e) {
            log.error("查询异常={}", e);
        }
        return videos;
    }

    private void formater(List<Video> videos) {
        if (videos != null && videos.size() > 0) {
            for (Video video1 : videos) {
                if ("0".equals(video1.getFileLength()) || video1.getFileLength() == null) {
                    video1.setFileLength("0MB");
                } else if (video1.getFileLength().contains(".")) {
                    video1.setFileLength(video1.getFileLength() + "MB");
                } else {
                    video1.setFileLength(sizeFormatNum2String(Long.valueOf(video1.getFileLength())));
                }
                if (video1.getFileDuration() != null && video1.getFileDuration() > 0) {
                    Long fileDuration = video1.getFileDuration();// 时间毫秒数需要转10:05:02
                    String str = formatTime(fileDuration);
                    video1.setFormatToTime(str);
                } else {
                    video1.setFormatToTime("00:00:00");
                }
            }
        }
    }

    @Override
    public List<Video> selectCaseVideo(Video video1) {

        return videoMapper.selectCaseVideo(video1);
    }

    @Override
    public List<Video> selectLawEnforcementVideo(Video video1) {
        return videoMapper.selectLawEnforcementVideo(video1);
    }

    @Override
    public List<Video> selectPublicVideo(Video video1) {
        return videoMapper.selectPublicVideo(video1);
    }

    @Override
    public List<Video> selectCaseByCode(String caseCode) {

        return videoMapper.selectCaseByCode(caseCode);
    }

    @Override
    public int deleteVideoById(String id, String videoSource) {
        int b = 0;
        if (videoSource.equals("0901")) {
            b = videoMapper.deleteLawEnforcementVideo(id);// 删除执法视频
        }
        if (videoSource.equals("0902")) {
            b = videoMapper.deletePublicVideo(id);// 删除公共视频
        }
        if (videoSource.equals("0903")) {
            b = videoMapper.deleteCaseVideo(id);// 删除办案视频
        }

        if (videoSource.equals("0904")) {
            b = videoMapper.deleteCarVideo(id);// 删除车载视频
        }

        if (videoSource.equals("0905")) {
            b = videoMapper.deleteOtherVideo(id);// 删除其他视频
        }
        return b;
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public int updateVideoRelationById(Video video) {
        int b = 0;
        if (video.getVideoSource().equals("0901")) {
            b = videoMapper.updateLawEnforcementVideoRelationById(video);// 更新执法视频
        }
        if (video.getVideoSource().equals("0902")) {
            b = videoMapper.updatePublicVideoRelationById(video);// 更新公共视频
        }
        if (video.getVideoSource().equals("0903")) {
            b = videoMapper.updateCaseVideo(video);// 更新办案视频
        }

        if (video.getVideoSource().equals("0904")) {
            b = videoMapper.updateCarVideo(video);// 更新车载视频
        }

        if (video.getVideoSource().equals("0905")) {
            b = videoMapper.updateOtherVideo(video);// 更新其他视频
        }

        Video selectVideoInfo = videoMapper.selectVideoInfo(video);
        String watermarkVideoPath = selectVideoInfo.getWatermarkVideoPath();
        String watermarkThumburl = selectVideoInfo.getWatermarkThumburl();
        String fileName = selectVideoInfo.getFileName();
        String trueName = watermarkVideoPath.substring(watermarkVideoPath.lastIndexOf("/") + 1);
        String fileType = watermarkVideoPath.substring(watermarkVideoPath.lastIndexOf("."));

        MaterialType mt = maTypeMapper.findById(video.getMaterialTypeId());
        String rootPath = mt.getCasename() + "-" + mt.getUploadpoliceid() + "-" + mt.getCasecode()
                + File.separator + mt.getCaseSuspectName() + File.separator + mt.getMaterialtypename();

        MaterialTypeDocument document = MaterialTypeDocument.builder().id(StringUtil.generatorUUID())
                .materialtypeid(video.getMaterialTypeId()).documentname(video.getDocumentName()).count(1).build();

        // 文件存放位置
        String path = ConstantUtil.FILE_PATH + rootPath + File.separator + document.getDocumentname() + File.separator + trueName;

        int pathLastIndex = path.lastIndexOf(File.separator);
        int lastIndex = watermarkThumburl.lastIndexOf("/");

        if (ConstantUtil.XSKYRESTORAGE) {
            // 设置新的Metadata
            ObjectMetadata meta = new ObjectMetadata();
            try {
                URL url = new URL(watermarkVideoPath);
                URLConnection urlConnection = url.openConnection();

                // 兼容win
                path = path.replace("\\", "/");
                watermarkVideoPath = path;
                meta.setContentType(urlConnection.getContentType());
                xskyService.uploadObjectForInputStream(ConstantUtil.XSKY_BUCKET_DOSSIER, path, urlConnection.getInputStream(), meta);

                url = new URL(watermarkThumburl);
                urlConnection = url.openConnection();
                path = path.substring(0, pathLastIndex) + watermarkThumburl.substring(lastIndex);
                watermarkThumburl = path;
                meta.setContentType(urlConnection.getContentType());
                xskyService.uploadObjectForInputStream(ConstantUtil.XSKY_BUCKET_DOSSIER, path, urlConnection.getInputStream(), meta);

            } catch (Exception e) {
                throw new RuntimeException(ResultEnum.XSKYUPLOADFAIL.getMsg(), e);
            }
        } else {
            try {
                URL url = new URL(watermarkVideoPath);
                URLConnection urlConnection = url.openConnection();
                File file = new File(path);
                // 创建文件夹目录
                file.getParentFile().mkdirs();
                // 复制文件
                FileUtil.copyInputStreamFile(urlConnection.getInputStream(), file);
                watermarkVideoPath = path;
                path = path.substring(0, pathLastIndex) + File.separator + watermarkThumburl.substring(lastIndex + 1);
                url = new URL(watermarkThumburl);
                urlConnection = url.openConnection();
                FileUtil.copyInputStreamFile(urlConnection.getInputStream(), new File(path));
                watermarkThumburl = path;

            } catch (Exception e) {
                throw new RuntimeException("复制文件到电子卷宗下异常：", e);
            }
        }

        // 添加关联的数据到电子卷宗
        try {
            if (fileMapper.addFile(
                    MaterialFile.builder().id(StringUtil.generatorUUID())
                            .materialtypedocumentid(document.getId()).filename(fileName)
                            .filetype(fileType).url(ConstantUtil.XSKYRESTORAGE ? (ConstantUtil.XSKY_PREPATH_URL + watermarkVideoPath) : watermarkVideoPath)
                            .thumbnailpath(ConstantUtil.XSKYRESTORAGE ? (ConstantUtil.XSKY_PREPATH_URL + watermarkThumburl) : watermarkThumburl).build()) > 0) {
                documentMapper.addDocument(document);
            }
        } catch (Exception e) {
            log.info("updateVideoRelationById 事务回滚:{}", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return b;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public int editVideoById(Video video) {
        int b = 0;

        if (video.getVideoSource().equals("0901")) {
            if (!StringUtil.isEmpty(video.getCorrelationCaseCode())
                    && !StringUtil.isEmpty(video.getCorrelationSuspectId())) {
                video.setCorrelationStatus("1");
            }
            b = videoMapper.editLawEnforcementVideoRelationById(video);// 编辑执法视频
        }

        if (video.getVideoSource().equals("0902")) {
            if (!StringUtil.isEmpty(video.getCorrelationCaseCode())
                    && !StringUtil.isEmpty(video.getCorrelationSuspectId())) {
                video.setCorrelationStatus("1");
            }
            b = videoMapper.editPublicVideoRelationById(video);// 编辑公共视频
        }
        if (video.getVideoSource().equals("0903")) {
            if (!StringUtil.isEmpty(video.getCorrelationCaseCode())
                    && !StringUtil.isEmpty(video.getCorrelationSuspectId())) {
                video.setCorrelationStatus("1");
            }
            b = videoMapper.editCaseVideo(video);// 编辑办案视频
        }

        if (video.getVideoSource().equals("0904")) {
            if (!StringUtil.isEmpty(video.getCorrelationCaseCode())
                    && !StringUtil.isEmpty(video.getCorrelationSuspectId())) {
                video.setCorrelationStatus("1");
            }
            b = videoMapper.editCarVideo(video);// 编辑车载视频
        }

        if (video.getVideoSource().equals("0905")) {
            if (!StringUtil.isEmpty(video.getCorrelationCaseCode())
                    && !StringUtil.isEmpty(video.getCorrelationSuspectId())) {
                video.setCorrelationStatus("1");
            }
            b = videoMapper.editOtherVideo(video);// 编辑其他视频
        }
//        } else {
//            if (video.getVideoSource().equals("0902")) {
//                PubliceVideo publiceVideo = videoMapper.selectPublicVideoById(video.getId());// 查询公共视频信息
//                videoMapper.deletePublicVideo(video.getId());// 删除公共视频
//
//                if (video.getEditVideoSource().equals("0903")) {
//                    publiceVideo.setOrgNo(video.getOrgNo());
//                    publiceVideo.setVideoSource(video.getVideoSource());
//                    publiceVideo.setCreateDate(video.getCreateDate());
//                    publiceVideo.setFileName(video.getFileName());
//                    publiceVideo.setFileType(video.getFileType());
//                    publiceVideo.setCorrelationCaseCode(video.getCorrelationCaseCode());
//                    publiceVideo.setCorrelationSuspectId(video.getCorrelationSuspectId());
//                    publiceVideo.setVideoSource("0903");
//                    if (!StringUtil.isEmpty(video.getCorrelationCaseCode())
//                            && !StringUtil.isEmpty(video.getCorrelationSuspectId())) {
//                        publiceVideo.setCorrelationStatus("1");
//                    }
//                    publiceVideo.setId(StringUtil.generatorUUID());
//                    b = videoMapper.insertCaseVideo(publiceVideo);// 新增办案视频
//                }
//
//                if (video.getEditVideoSource().equals("0904")) {
//                    publiceVideo.setOrgNo(video.getOrgNo());
//                    publiceVideo.setVideoSource(video.getVideoSource());
//                    publiceVideo.setCreateDate(video.getCreateDate());
//                    publiceVideo.setFileName(video.getFileName());
//                    publiceVideo.setFileType(video.getFileType());
//                    publiceVideo.setCorrelationCaseCode(video.getCorrelationCaseCode());
//                    publiceVideo.setCorrelationSuspectId(video.getCorrelationSuspectId());
//                    publiceVideo.setVideoSource("0904");
//                    if (!StringUtil.isEmpty(video.getCorrelationCaseCode())
//                            && !StringUtil.isEmpty(video.getCorrelationSuspectId())) {
//                        publiceVideo.setCorrelationStatus("1");
//                    }
//                    publiceVideo.setId(StringUtil.generatorUUID());
//                    // videoMapper.deletePublicVideo(video.getId());//删除公共视频
//                    b = videoMapper.insertCarVideo(publiceVideo);// 新增车载视频
//                }
//                if (video.getEditVideoSource().equals("0905")) {
//                    publiceVideo.setOrgNo(video.getOrgNo());
//                    publiceVideo.setVideoSource(video.getVideoSource());
//                    publiceVideo.setCreateDate(video.getCreateDate());
//                    publiceVideo.setFileName(video.getFileName());
//                    publiceVideo.setFileType(video.getFileType());
//                    publiceVideo.setCorrelationCaseCode(video.getCorrelationCaseCode());
//                    publiceVideo.setCorrelationSuspectId(video.getCorrelationSuspectId());
//                    publiceVideo.setVideoEquipment(video.getVideoEquipment());
//                    publiceVideo.setVideoSource("0905");
//                    if (!StringUtil.isEmpty(video.getCorrelationCaseCode())
//                            && !StringUtil.isEmpty(video.getCorrelationSuspectId())) {
//                        publiceVideo.setCorrelationStatus("1");
//                    }
//                    // videoMapper.deletePublicVideo(video.getId());//删除执法视频
//                    publiceVideo.setId(StringUtil.generatorUUID());
//                    b = videoMapper.insertOtherVideo(publiceVideo);// 新增其他视频
//                }
//            }
//            if (video.getVideoSource().equals("0903")) {
//                PubliceVideo publiceVideo = videoMapper.selectCaseVideoById(video.getId());// 查询办案视频
//                videoMapper.deleteCaseVideo(video.getId());// 删除办案视频
//                if (video.getEditVideoSource().equals("0902")) {
//                    publiceVideo.setOrgNo(video.getOrgNo());
//                    publiceVideo.setVideoSource(video.getVideoSource());
//                    publiceVideo.setCreateDate(video.getCreateDate());
//                    publiceVideo.setFileName(video.getFileName());
//                    publiceVideo.setFileType(video.getFileType());
//                    publiceVideo.setCorrelationCaseCode(video.getCorrelationCaseCode());
//                    publiceVideo.setCorrelationSuspectId(video.getCorrelationSuspectId());
//                    publiceVideo.setVideoSource("0902");
//                    if (!StringUtil.isEmpty(video.getCorrelationCaseCode())
//                            && !StringUtil.isEmpty(video.getCorrelationSuspectId())) {
//                        publiceVideo.setCorrelationStatus("1");
//                    }
//                    b = videoMapper.insertPublicVideo(publiceVideo);// 新增笔录录像视频文件视频
//                }
//                if (video.getEditVideoSource().equals("0904")) {
//                    publiceVideo.setOrgNo(video.getOrgNo());
//                    publiceVideo.setVideoSource(video.getVideoSource());
//                    publiceVideo.setCreateDate(video.getCreateDate());
//                    publiceVideo.setFileName(video.getFileName());
//                    publiceVideo.setFileType(video.getFileType());
//                    publiceVideo.setCorrelationCaseCode(video.getCorrelationCaseCode());
//                    publiceVideo.setCorrelationSuspectId(video.getCorrelationSuspectId());
//                    publiceVideo.setVideoSource("0904");
//                    if (!StringUtil.isEmpty(video.getCorrelationCaseCode())
//                            && !StringUtil.isEmpty(video.getCorrelationSuspectId())) {
//                        publiceVideo.setCorrelationStatus("1");
//                    }
//                    // videoMapper.deleteCaseVideo(video.getId());//删除办案视频
//                    b = videoMapper.insertCaseVideo(publiceVideo);// 新增车载视频
//                }
//                if (video.getEditVideoSource().equals("0905")) {
//                    publiceVideo.setOrgNo(video.getOrgNo());
//                    publiceVideo.setVideoSource(video.getVideoSource());
//                    publiceVideo.setCreateDate(video.getCreateDate());
//                    publiceVideo.setFileName(video.getFileName());
//                    publiceVideo.setFileType(video.getFileType());
//                    publiceVideo.setCorrelationCaseCode(video.getCorrelationCaseCode());
//                    publiceVideo.setCorrelationSuspectId(video.getCorrelationSuspectId());
//                    publiceVideo.setVideoEquipment(video.getVideoEquipment());
//                    publiceVideo.setVideoSource("0905");
//                    if (!StringUtil.isEmpty(video.getCorrelationCaseCode())
//                            && !StringUtil.isEmpty(video.getCorrelationSuspectId())) {
//                        publiceVideo.setCorrelationStatus("1");
//                    }
//                    // videoMapper.deleteCaseVideo(video.getId());//删除办案视频
//                    b = videoMapper.insertOtherVideo(publiceVideo);// 新增其他视频
//                }
//            }
//
//            if (video.getVideoSource().equals("0904")) {
//                PubliceVideo publiceVideo = videoMapper.selectCarVideoById(video.getId());
//                videoMapper.deleteCarVideo(video.getId());// 删除车载视频
//                if (video.getEditVideoSource().equals("0902")) {
//                    publiceVideo.setOrgNo(video.getOrgNo());
//                    publiceVideo.setVideoSource(video.getVideoSource());
//                    publiceVideo.setCreateDate(video.getCreateDate());
//                    publiceVideo.setFileName(video.getFileName());
//                    publiceVideo.setFileType(video.getFileType());
//                    publiceVideo.setCorrelationCaseCode(video.getCorrelationCaseCode());
//                    publiceVideo.setCorrelationSuspectId(video.getCorrelationSuspectId());
//                    publiceVideo.setVideoSource("0905");
//                    publiceVideo.setVideoEquipment(video.getVideoEquipment());
//                    if (!StringUtil.isEmpty(video.getCorrelationCaseCode())
//                            && !StringUtil.isEmpty(video.getCorrelationSuspectId())) {
//                        publiceVideo.setCorrelationStatus("1");
//                    }
//                    // videoMapper.deleteCarVideo(video.getId());//删除车载视频
//                    b = videoMapper.insertPublicVideo(publiceVideo);// 新增公共视频
//                }
//                if (video.getEditVideoSource().equals("0903")) {
//                    publiceVideo.setOrgNo(video.getOrgNo());
//                    publiceVideo.setVideoSource(video.getVideoSource());
//                    publiceVideo.setCreateDate(video.getCreateDate());
//                    publiceVideo.setFileName(video.getFileName());
//                    publiceVideo.setFileType(video.getFileType());
//                    publiceVideo.setCorrelationCaseCode(video.getCorrelationCaseCode());
//                    publiceVideo.setCorrelationSuspectId(video.getCorrelationSuspectId());
//                    publiceVideo.setVideoEquipment(video.getVideoEquipment());
//                    publiceVideo.setVideoSource("0903");
//                    if (!StringUtil.isEmpty(video.getCorrelationCaseCode())
//                            && !StringUtil.isEmpty(video.getCorrelationSuspectId())) {
//                        publiceVideo.setCorrelationStatus("1");
//                    }
//                    // videoMapper.deleteCarVideo(video.getId());//删除车载视频
//                    b = videoMapper.insertCaseVideo(publiceVideo);// 新增车载视频
//                }
//                if (video.getEditVideoSource().equals("0905")) {
//                    publiceVideo.setOrgNo(video.getOrgNo());
//                    publiceVideo.setVideoSource(video.getVideoSource());
//                    publiceVideo.setCreateDate(video.getCreateDate());
//                    publiceVideo.setFileName(video.getFileName());
//                    publiceVideo.setFileType(video.getFileType());
//                    publiceVideo.setCorrelationCaseCode(video.getCorrelationCaseCode());
//                    publiceVideo.setCorrelationSuspectId(video.getCorrelationSuspectId());
//                    publiceVideo.setVideoEquipment(video.getVideoEquipment());
//                    publiceVideo.setVideoSource("0905");
//                    if (!StringUtil.isEmpty(video.getCorrelationCaseCode())
//                            && !StringUtil.isEmpty(video.getCorrelationSuspectId())) {
//                        publiceVideo.setCorrelationStatus("1");
//                    }
//                    // videoMapper.deleteCarVideo(video.getId());//删除车载视频
//                    b = videoMapper.insertOtherVideo(publiceVideo);// 新增其他视频
//                }
//            }
//            if (video.getVideoSource().equals("0905")) {
//                PubliceVideo publiceVideo = videoMapper.selectOtherVideoById(video.getId());
//                videoMapper.deleteOtherVideo(video.getId());// 删除其他视频
//                if (video.getEditVideoSource().equals("0902")) {
//                    publiceVideo.setOrgNo(video.getOrgNo());
//                    publiceVideo.setVideoSource(video.getVideoSource());
//                    publiceVideo.setCreateDate(video.getCreateDate());
//                    publiceVideo.setFileName(video.getFileName());
//                    publiceVideo.setFileType(video.getFileType());
//                    publiceVideo.setCorrelationCaseCode(video.getCorrelationCaseCode());
//                    publiceVideo.setCorrelationSuspectId(video.getCorrelationSuspectId());
//                    publiceVideo.setVideoEquipment(video.getVideoEquipment());
//                    publiceVideo.setVideoSource("0902");
//                    if (!StringUtil.isEmpty(video.getCorrelationCaseCode())
//                            && !StringUtil.isEmpty(video.getCorrelationSuspectId())) {
//                        publiceVideo.setCorrelationStatus("1");
//                    }
//                    b = videoMapper.insertPublicVideo(publiceVideo);// 新增公共视频
//                }
//                if (video.getEditVideoSource().equals("0903")) {
//                    publiceVideo.setOrgNo(video.getOrgNo());
//                    publiceVideo.setVideoSource(video.getVideoSource());
//                    publiceVideo.setCreateDate(video.getCreateDate());
//                    publiceVideo.setFileName(video.getFileName());
//                    publiceVideo.setFileType(video.getFileType());
//                    publiceVideo.setCorrelationCaseCode(video.getCorrelationCaseCode());
//                    publiceVideo.setCorrelationSuspectId(video.getCorrelationSuspectId());
//                    publiceVideo.setVideoEquipment(video.getVideoEquipment());
//                    publiceVideo.setVideoSource("0903");
//                    if (!StringUtil.isEmpty(video.getCorrelationCaseCode())
//                            && !StringUtil.isEmpty(video.getCorrelationSuspectId())) {
//                        publiceVideo.setCorrelationStatus("1");
//                    }
//                    // videoMapper.deleteOtherVideo(video.getId());//删除其他视频
//                    b = videoMapper.insertCaseVideo(publiceVideo);// 新增车载视频
//                }
//                if (video.getEditVideoSource().equals("0904")) {
//                    publiceVideo.setOrgNo(video.getOrgNo());
//                    publiceVideo.setVideoSource(video.getVideoSource());
//                    publiceVideo.setCreateDate(video.getCreateDate());
//                    publiceVideo.setFileName(video.getFileName());
//                    publiceVideo.setFileType(video.getFileType());
//                    publiceVideo.setCorrelationCaseCode(video.getCorrelationCaseCode());
//                    publiceVideo.setCorrelationSuspectId(video.getCorrelationSuspectId());
//                    publiceVideo.setVideoEquipment(video.getVideoEquipment());
//                    publiceVideo.setVideoSource("0904");
//                    if (!StringUtil.isEmpty(video.getCorrelationCaseCode())
//                            && !StringUtil.isEmpty(video.getCorrelationSuspectId())) {
//                        publiceVideo.setCorrelationStatus("1");
//                    }
//                    // videoMapper.deleteOtherVideo(video.getId());//删除其他视频
//                    b = videoMapper.insertCarVideo(publiceVideo);// 新增其他视频
//                }
//            }

        //}

        return b;
    }

    @Override
    public Map selectVideoById(String id, String videoSource) {
        Map map = new HashMap();
        if (videoSource.equals("0901")) {
            Video video = videoMapper.selectLawEnforcementVideoById(id);// 查询执法视频
            map.put("video", video);
        }
        if (videoSource.equals("0902")) {
            PubliceVideo publiceVideo = videoMapper.selectPublicVideoById(id);// 查询公共视频
            map.put("publiceVideo", publiceVideo);
        }
        if (videoSource.equals("0903")) {
            PubliceVideo publiceVideo = videoMapper.selectCaseVideoById(id);// 查询办案视频
            map.put("publiceVideo", publiceVideo);
        }

        if (videoSource.equals("0904")) {
            PubliceVideo publiceVideo = videoMapper.selectCarVideoById(id);// 查询车载视频
            map.put("publiceVideo", publiceVideo);
        }

        if (videoSource.equals("0905")) {
            PubliceVideo publiceVideo = videoMapper.selectOtherVideoById(id);// 查询其他视频
            map.put("publiceVideo", publiceVideo);
        }
        return map;
    }

    @Override
    public int uploadVideo(PubliceVideo vo, MultipartFile b) throws IOException {
        int value = 0;
        if (vo.getVideoSource().equals("0901")) {
            if (!StringUtil.isEmpty(vo.getCorrelationCaseCode()) && !StringUtil.isEmpty(vo.getCorrelationSuspectId())) {

                vo.setCorrelationStatus("1");
            }
            value = videoMapper.insertLawEnforcementVideo(vo);
        }
        if (vo.getVideoSource().equals("0902")) {
            if (!StringUtil.isEmpty(vo.getCorrelationCaseCode()) && !StringUtil.isEmpty(vo.getCorrelationSuspectId())) {
                vo.setCorrelationStatus("1");
            }
            value = videoMapper.insertPublicVideo(vo);
        }
        if (vo.getVideoSource().equals("0903")) {
            if (!StringUtil.isEmpty(vo.getCorrelationCaseCode()) && !StringUtil.isEmpty(vo.getCorrelationSuspectId())) {
                vo.setCorrelationStatus("1");
            }
            value = videoMapper.insertCaseVideo(vo);
        }
        if (vo.getVideoSource().equals("0904")) {
            if (!StringUtil.isEmpty(vo.getCorrelationCaseCode()) && !StringUtil.isEmpty(vo.getCorrelationSuspectId())) {
                vo.setCorrelationStatus("1");
            }
            value = videoMapper.insertCarVideo(vo);
        }
        if (vo.getVideoSource().equals("0905")) {
            if (!StringUtil.isEmpty(vo.getCorrelationCaseCode()) && !StringUtil.isEmpty(vo.getCorrelationSuspectId())) {
                vo.setCorrelationStatus("1");
            }
            // 自定义的文件名称
            String trueFileName = String.valueOf(System.currentTimeMillis());

            boolean bl = false;
            //生成原视频和图片缩略图
            if (vo.getFileType().equals("2") || vo.getFileType().equals("3")) {
                if (vo.getFileType().equals("2")) {
                    String videoThumb = "";
                    // 缩略图输入流
                    ByteArrayInputStream byteArrayInputStream = null;
                    // 缩略图输出流
                    ByteArrayOutputStream byteArrayOutputStream = null;

                    //判断是否使用XSKY存储
//                    if (ConstantUtil.XSKYRESTORAGE) {
                    if (bl) {
                        try {
                            byteArrayOutputStream = new ByteArrayOutputStream();
                            byteArrayInputStream = new ByteArrayInputStream(b.getBytes());

                            VideoImageUtil.randomGrabberFFmpegImage(
                                    new FFmpegFrameGrabber(byteArrayInputStream), VideoImageUtil.MOD, byteArrayOutputStream);
                            ObjectMetadata meta = new ObjectMetadata();
                            meta.setContentType(ContentType.IMAGE_PNG.getMimeType());
                            xskyService.uploadObjectForInputStream(ConstantUtil.XSKY_BUCKET_DOSSIER, vo.getPlayPosition(), byteArrayOutputStream.toByteArray(), meta);
                            //缩略图相对地址
                            vo.setThumb(ConstantUtil.XSKY_PREPATH_URL + vo.getPlayPosition());
                            vo.setWatermarkThumb(ConstantUtil.XSKY_PREPATH_URL + vo.getPlayPosition());
                            vo.setWatermarkPlayPosition(vo.getPlayPosition());
                            //缩略图绝对地址
                            vo.setThumburl(ConstantUtil.XSKY_PREPATH_URL + vo.getPlayPosition());
                            vo.setWatermarkThumburl(ConstantUtil.XSKY_PREPATH_URL + vo.getPlayPosition());
                            vo.setWatermarkVideoPath(vo.getVideoPath());
                        } catch (Exception e) {
                            log.error(ResultEnum.XSKYUPLOADFAIL.getMsg(), e);
                            return ResultEnum.FAIL.getCode();
                        }
                    } else {

                        try {
                            videoThumb = VideoImageUtil.randomGrabberFFmpegImage(vo.getPlayPosition(), VideoImageUtil.MOD);
                            //缩略图相对地址
                            vo.setThumb(videoThumb);
                            vo.setWatermarkThumb(videoThumb);
                            vo.setWatermarkPlayPosition(vo.getPlayPosition());
                            //缩略图绝对地址
                            vo.setThumburl(ConstantUtil.PDF_PATH + videoThumb);
                            vo.setWatermarkThumburl(ConstantUtil.PDF_PATH + videoThumb);
                            vo.setWatermarkVideoPath(vo.getVideoPath());
                        } catch (Exception e) {
                            log.error("生成视频缩略图异常:{}", e);
                        }
                    }
                } else {
                    String videoThumb = "";
                    // 缩略图输入流
                    ByteArrayInputStream byteArrayInputStream = null;
                    // 缩略图输出流
                    ByteArrayOutputStream byteArrayOutputStream = null;
//                    if (ConstantUtil.XSKYRESTORAGE) {
                    if (bl) {

                        byteArrayOutputStream = new ByteArrayOutputStream();
                        byteArrayInputStream = new ByteArrayInputStream(b.getBytes());
                        Thumbnails.of(byteArrayInputStream).size(200, 300).toOutputStream(byteArrayOutputStream);
                        ObjectMetadata meta = new ObjectMetadata();
                        meta.setContentType(ContentType.IMAGE_PNG.getMimeType());
                        xskyService.uploadObjectForInputStream(ConstantUtil.XSKY_BUCKET_DOSSIER, vo.getPlayPosition(), byteArrayOutputStream.toByteArray(), meta);
                        vo.setThumb(ConstantUtil.XSKY_PREPATH_URL + vo.getPlayPosition());
                        vo.setWatermarkThumb(ConstantUtil.XSKY_PREPATH_URL + vo.getPlayPosition());
                        vo.setWatermarkPlayPosition(vo.getPlayPosition());
                        //缩略图绝对地址
                        vo.setThumburl(ConstantUtil.XSKY_PREPATH_URL + vo.getPlayPosition());
                        vo.setWatermarkThumburl(ConstantUtil.XSKY_PREPATH_URL + vo.getPlayPosition());
                        vo.setWatermarkVideoPath(vo.getVideoPath());
                    } else {
                        //图片和加水印的缩略图地址
                        String thumbnailpath = ConstantUtil.VIDEOMANAGE_PATH;// 缩略图的存放位置
                        String thumbnailtruePath = thumbnailpath + trueFileName + "thumbnail" + ".jpg";
                        File newFile1 = new File(thumbnailpath);
                        if (!newFile1.exists()) {
                            newFile1.mkdirs();
                        }
                        try {
                            Thumbnails.of(vo.getPlayPosition()).size(200, 300).toFile(thumbnailtruePath);
                            //图片缩略图相对路径拼接路劲
                            vo.setThumb(thumbnailpath + trueFileName + "thumbnail" + ".jpg");
                            vo.setWatermarkThumb(thumbnailpath + trueFileName + "thumbnail" + ".jpg");
                            //图片缩略图绝对路径
                            vo.setThumburl(ConstantUtil.PDF_PATH + thumbnailtruePath);
                            vo.setWatermarkThumburl(ConstantUtil.PDF_PATH + thumbnailtruePath);
                            vo.setWatermarkPlayPosition(vo.getPlayPosition());
                            vo.setWatermarkVideoPath(vo.getVideoPath());
                        } catch (IOException e) {
                            log.info("生成图片缩略图异常");
                        }
                    }
                }
            }
            // 音频和视频播放时长
            if (vo.getFileType().equals("1") || vo.getFileType().equals("2")) {
                long fileDuration = ReadVideoTimeMs(b);
                vo.setFileDuration(fileDuration);
            }
            //音频生成的图片
            if (vo.getFileType().equals("1")) {
//                if (ConstantUtil.XSKYRESTORAGE) {
                if (bl) {
                    vo.setWatermarkPlayPosition(vo.getPlayPosition());
                    vo.setWatermarkVideoPath(vo.getVideoPath());
                    vo.setThumb(ConstantUtil.WEB_MP3FILE_PATH);
                    vo.setThumburl(ConstantUtil.WEB_MP3FILE_PATH);
                    vo.setWatermarkThumb(ConstantUtil.WEB_MP3FILE_PATH);
                    vo.setWatermarkThumburl(ConstantUtil.WEB_MP3FILE_PATH);
                } else {
                    vo.setWatermarkPlayPosition(vo.getPlayPosition());
                    vo.setWatermarkVideoPath(vo.getVideoPath());
                    vo.setThumb(ConstantUtil.VIDEOMANAGE_PATH + "voice.png");
                    vo.setThumburl(ConstantUtil.returnIp() + ConstantUtil.VIDEOMANAGE_PATH + "voice.png");
                    vo.setWatermarkThumb(ConstantUtil.VIDEOMANAGE_PATH + "voice.png");
                    vo.setWatermarkThumburl(ConstantUtil.returnIp() + ConstantUtil.VIDEOMANAGE_PATH + "voice.png");
                }
            }
            //求文件长度

            long fileLength = b.getSize();
            vo.setFileLength(fileLength);
            vo.setWatermarkFileLength(fileLength);
            value = videoMapper.insertOtherVideo(vo);
        }
        return value;
    }

    /**
     * @Description: 获取视频时长(ms)
     * @author: Hanweihu
     * @date: 2019/7/30 8:35
     * @params: [file]
     * @return: long
     */
    public long ReadVideoTimeMs(MultipartFile file) {
        Encoder encoder = new Encoder();
        long ms = 0;
        try {
            // 获取文件类型
            String fileName = file.getContentType();
            // 获取文件后缀
            String pref = fileName.indexOf("/") != -1 ? fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length()) : null;
            String prefix = "." + pref;
            // 用uuid作为文件名，防止生成的临时文件重复
            final File excelFile = File.createTempFile(UUID.randomUUID().toString().replace("-", ""), prefix);
            // MultipartFile to File
            file.transferTo(excelFile);
            MultimediaInfo m = encoder.getInfo(excelFile);
            ms = m.getDuration();
            //程序结束时，删除临时文件
            deleteFile(excelFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ms;
    }


    /**
     * @Description: 删除文件
     * @author: Hanweihu
     * @date: 2019/7/30 8:35
     * @params: [files]
     * @return: void
     */
    private static void deleteFile(File... files) {
        for (File file : files) {
            if (file.exists()) {
                file.delete();
            }
        }
    }


    @Override
    public List<PoliceVo> selectPoliceByUnitcodes(String unitCodes, String policeCode) {
        String[] array = unitCodes.split(",");
        int weights = videoMapper.selectPoliceManWeight(policeCode);
        List<PoliceVo> list = null;
        if (weights > 4) {
            list = videoMapper.selectPoliceMan(policeCode);
        } else {
            list = videoMapper.selectPoliceByUnitcodes(array, policeCode);
        }
        return list;
    }

    @Override
    public List<PoliceVo> selectUnicodeAndName() {
        List<PoliceVo> list = videoMapper.selectUnicodeAndName();
        return list;
    }

    @Override
    public String selectPercentage(String policeId) {
        int count = 0;
        int avCount = 0;
        String relation = "";
        List<AuditResult> auditResults = auditResultMapper.selectAllAuditByPoliceId(policeId);
        count = auditResults.size();
        for (AuditResult vos : auditResults) {
            if (vos != null) {
                int i = auditResultMapper.selectAvCount(vos.getCaseCode(), vos.getSuspectId(), vos.getPoliceId());
                if (i != 0) {
                    avCount++;
                }
            }
        }
        if (count == 0 && avCount == 0) {
            relation = "0%";
        }
        if (count != 0 && avCount == 0) {
            relation = "0%";
        }
        if (count != 0 && avCount != 0) {
            // 创建一个数值格式化对象
            NumberFormat numberFormat = NumberFormat.getInstance();
            // 设置精确到小数点后2位
            numberFormat.setMaximumFractionDigits(2);
            String result = numberFormat.format((float) avCount / (float) count * 100);
            relation = result + "%";
        }
        return relation;
    }

    @Override
    public List<TSuspec> aVCorrelation(TSuspec vo) {
        log.info("vo:{}", JSONObject.toJSONString(vo));
        List<TSuspec> list = null;
        try {
            PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
            list = tSuspecMapper.countCase(vo);//查询民警下所有的案件
            for (TSuspec tsuspect : list) {
                if (tsuspect != null) {
                    int avCount = 0;
                    Map map = new HashMap();
                    String caseCode = tsuspect.getCaseCode();
                    map.put("caseCode", caseCode);
                    int count = auditResultMapper.selectAudit(map);// 查询该案件所有卷宗数量
                    List<AuditResult> auditResults = auditResultMapper.selectAllAudit(caseCode);
                    for (AuditResult vos : auditResults) {
                        String suspectId = vos.getSuspectId();
                        if (vos != null) {
                            int i = auditResultMapper.selectAvCount(caseCode, suspectId, vos.getPoliceId());//遍历每一个卷宗查询它是否关联好
                            if (i != 0) {
                                avCount++;
                            }
                        }
                    }
                    if (count == avCount) {
                        tsuspect.setPercentage("100%");
                    }
                    if (avCount == 0 && count > 0) {
                        tsuspect.setPercentage("0%");
                    }
                    if (count != 0 && avCount != 0 && count > avCount) {
                        // 创建一个数值格式化对象
                        NumberFormat numberFormat = NumberFormat.getInstance();
                        // 设置精确到小数点后2位
                        numberFormat.setMaximumFractionDigits(2);
                        String result = numberFormat.format((float) avCount / (float) count * 100);
                        tsuspect.setPercentage(result + "%");
                    }
                }
            }
        } catch (Exception e) {
            log.error("查询异常={}", e);
        }
        return list;

    }

    @Override
    public List<AuditResult> selectAuditDetailsByCasecode(AuditResult vo) {
        log.info("vo:{}", JSONObject.toJSONString(vo));
        List<AuditResult> list = null;
        try {
            PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
            list = auditResultMapper.selectAllAudit(vo.getCaseCode());
            for (AuditResult vos : list) {
                int i = auditResultMapper.selectAvCount(vos.getCaseCode(), vos.getSuspectId(), vos.getPoliceId());
                if (i != 0) {
                    vos.setRelationVideo(1);
                    log.info("vos:{}", vos + "-----------------------------------------------------------------------");
                } else {
                    vos.setRelationVideo(0);
                }

            }

        } catch (Exception e) {
            log.error("查询异常={}", e);
        }
        return list;
    }

    @Override
    public List<Video> updateRquestOrg() {
        List<Video> videos = videoMapper.selectNoIsMapping();
        for (Video vo : videos) {
            if (vo.getOrgNo().length() == 12) {
                int i = videoMapper.selectOrgNo(vo.getOrgNo());
                if (i != 0) {
                    vo.setOrgNoNew(vo.getOrgNo());
                    int j = videoMapper.updateOrgNo(vo);
                    System.out.println("更新绑定单位编号成功" + j);
                } else {
                    handle(vo);
                }
            } else {
                handle(vo);
            }

        }
        return null;
    }

    @Override
    public void syncSHYFilesToDossierFiles() {

        List<MaterialType> materialTypes = maTypeMapper.findMaterialByName("电话音频", "2020-09-25 14:25:34", "2020-09-27 14:25:34");
        // 去重之后的案件编号
        List<String> caseCodes = materialTypes.stream().map(MaterialType::getCasecode).distinct().collect(Collectors.toList());
        // 根据案件编号查询所有三合一文件
    }

    //单位处理
    public void handle(Video vo) {
        String str1 = videoMapper.selectByorgName(vo.getOrgName());//通过单位名称
        if (!StringUtil.isEmpty(str1)) {
            vo.setOrgNoNew(str1);
            vo.setIsMapping(1);
            int j = videoMapper.updateOrgNo(vo);
            System.out.println("更新绑定单位编号成功" + j);
        } else {
            String str = videoMapper.selectByPoliceNo(vo.getPoliceNo());//通过民警编号
            if (!StringUtil.isEmpty(str)) {
                vo.setOrgNoNew(str);
                vo.setIsMapping(1);
                int j = videoMapper.updateOrgNo(vo);
                System.out.println("更新绑定单位编号成功" + j);
            } else {
                String name = vo.getName();
                List<Video> list = videoMapper.selectByName(name);//通过民警姓名
                if (list != null && list.size() > 0) {
                    if (list.size() == 1) {
                        vo.setOrgNoNew(list.get(0).getOrgNo());
                        vo.setIsMapping(1);
                        int j = videoMapper.updateOrgNo(vo);
                        System.out.println("更新绑定单位编号成功" + j);
                    } else {
                        vo.setOrgNoNew("");
                        vo.setIsMapping(2);
                        int j = videoMapper.updateOrgNo(vo);
                        System.out.println("更新绑定单位编号成功" + j);
                        log.info("more police =  {}", JSONObject.toJSONString(list));
                    }
                } else {
                    log.info("empty police =  {}", JSONObject.toJSONString(vo));
                    vo.setOrgNoNew("");
                    vo.setIsMapping(3);
                    int j = videoMapper.updateOrgNo(vo);
                    System.out.println("更新绑定单位编号成功" + j);
                }
            }
        }
    }

    // long==> 616.19KB,3.73M
    public static String sizeFormatNum2String(long size) {
        String s = "";
        if (size > 1024 * 1024)
            s = String.format("%.2f", (double) size / pers) + "M";
        else
            s = String.format("%.2f", (double) size / (1024)) + "KB";
        return s;
    }

    /*
     * 毫秒转化
     */
    public static String formatTime(long ms) {

        int ss = 1000;
        int mi = ss * 60;
        int hh = mi * 60;
        int dd = hh * 24;

        long day = ms / dd;
        long hour = (ms - day * dd) / hh;
        long minute = (ms - day * dd - hour * hh) / mi;
        long second = (ms - day * dd - hour * hh - minute * mi) / ss;
        long milliSecond = ms - day * dd - hour * hh - minute * mi - second * ss;

        String strDay = day < 10 ? "0" + day : "" + day; // 天
        String strHour = hour < 10 ? "0" + hour : "" + hour;// 小时
        String strMinute = minute < 10 ? "0" + minute : "" + minute;// 分钟
        String strSecond = second < 10 ? "0" + second : "" + second;// 秒
        String strMilliSecond = milliSecond < 10 ? "0" + milliSecond : "" + milliSecond;// 毫秒
        strMilliSecond = milliSecond < 100 ? "0" + strMilliSecond : "" + strMilliSecond;

        return strHour + ":" + strMinute + ":" + strSecond;
    }

}